package interceptcrossing;

import java.io.*;
import java.util.*;

/**
 * Класс для чтения отрезков из файла.
 * Каждый отрезок задаётся четырьмя координатами, разделёнными хотя бы одним
 * пробельным символом в каждой строке.
 *
 * @author Igor Botyan
 */
public class InterceptFileReader {

	File file;

	public InterceptFileReader(File file) throws FileNotFoundException {
		if (!file.exists()) {
			throw new FileNotFoundException("Input file is not exist");
		}

		this.file = file;
	}

	public List<Intercept> readIntercepts() throws IOException {
		List<Intercept> ret = new LinkedList<Intercept>();

		BufferedReader reader = null;

		try {
			reader = new BufferedReader(new FileReader(this.file));
			String line;

			while ((line = reader.readLine()) != null) {
				ret.add(this.parseLine(line));
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		return ret;
	}

	private Intercept parseLine(String line) throws IOException {
		List<Double> coords = this.parseNumbers(line);
		try {

		} catch (NumberFormatException e) {
			throw new InputMismatchException(e.getMessage());
		}

		if (coords.size() != 4) {
			throw new IOException("Line must contain a 4 coordinates");
		}

		Point begin = new Point(coords.get(0), coords.get(1));
		Point end = new Point(coords.get(2), coords.get(3));

		return new Intercept(begin, end);
	}

	private List<Double> parseNumbers(String line) throws IOException {
		List<Double> ret = new ArrayList<Double>();
		Scanner numberScanner = new Scanner(line);

		try {
			for (int i = 0; i < 4; i++) {
				if (numberScanner.hasNextDouble()) {
					ret.add(numberScanner.nextDouble());
				}
			}
		} catch (InputMismatchException e) {
			throw new IOException(e);
		}

		return ret;
	}
}
